//
//  MapViewController.m
//  RunningMan
//
//  Created by dllo on 16/5/23.
//  Copyright © 2016年 JohnnyB. All rights reserved.
//
#define MAS_SHORTHAND
#define MAS_SHORTHAND_GLOBALS

#import "MapViewController.h"
#import <MAMapKit/MAMapKit.h>
#import "Header.h"
#import "PointsModel.h"
#import "WHRecord.h"
#import "WHStatusViewView.h"


typedef enum: NSUInteger{
    TrailStart,
    TrailEnd
}Trail;

@interface MapViewController ()<MAMapViewDelegate>

@property (nonatomic) CLLocationCoordinate2D centerCoordinate;

@property (nonatomic, strong) WHRecord *record;
/** 高德地图View **/
@property (nonatomic, strong) MAMapView *mapView;
/** 状态View **/
@property (nonatomic, strong) WHStatusViewView *statusView;

@property (nonatomic, strong) UIButton *lodationButton;//定位按钮
/** 记录上一次的位置 **/
@property (nonatomic, strong) CLLocation *preLocation;

@property (nonatomic, copy) NSMutableArray *points;

@property (nonatomic, copy) NSMutableArray *locationArrayM;

@property (nonatomic, assign) double averageSpeed;
/** 轨迹线 */
@property (nonatomic, strong) MAPolyline *polyLine;

/** 轨迹记录状态 */
@property (nonatomic, assign) Trail trail;

/** 起点大头针 */
@property (nonatomic, strong) MAPointAnnotation *startPoint;

/** 终点大头针 */
@property (nonatomic, strong) MAPointAnnotation *endPoint;

/** 累计步行时间 */
@property (nonatomic,assign) NSTimeInterval sumTime;

/** 累计步行距离 */
@property (nonatomic,assign) CGFloat sumDistance;



@end

@implementation MapViewController

-(void)viewWillDisappear:(BOOL)animated{
    
    _mapView.delegate = nil;
    _mapView = nil;
    _statusView = nil;
}


- (void)viewDidLoad {
    [super viewDidLoad];
//    self.view.backgroundColor = [UIColor redColor];
    self.navigationController.navigationBar.translucent = NO;

    [self initMapView];
//    [self initControls];
    [self setupNavigationProperty];
}

//地图
-(void)initMapView{
    //开发者 key
    [MAMapServices sharedServices].apiKey = @"08681425c12af1df5c4c3b955b24f8e1";
    _mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT /2)];
    _mapView.backgroundColor = [UIColor redColor];
    NSLog(@"%f", _mapView.frame.size.height);
    _statusView = [WHStatusViewView new];
    [self.view addSubview:_statusView.view];
    
    [_statusView.view makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.offset(SCREEN_HEIGHT/2 - 64);
        make.left.offset(0);
        make.right.offset(-0);
        make.height.offset(SCREEN_HEIGHT/2);
        
        
    }];
    NSLog(@"bbbbb%f", _statusView.view.frame.size.height);
//    _statusView.view.frame = CGRectMake(0, SCREEN_HEIGHT / 2 , SCREEN_WIDTH, SCREEN_HEIGHT / 2);
    
    _mapView.delegate = self;
    
    /**  地图布局 ***/
    
    //罗盘
    _mapView.compassOrigin = CGPointMake(_mapView.compassOrigin.x, 22);

    //比例尺原点位置
    _mapView.scaleOrigin = CGPointMake(_mapView.scaleOrigin.x, 22);

    
//    _mapView.showsUserLocation = YES;// YES为打开定位  NO为关闭定位
    
//    定位用户位置的模式           追踪用户的location更新
    _mapView.userTrackingMode = MAUserTrackingModeFollow;
    
    //设定定位的最小更新距离
    _mapView.distanceFilter = 5;
    
    //精度圈
//    _mapView.customizeUserLocationAccuracyCircleRepresentation = YES;
    
    self.trail = TrailEnd;
   
//    _mapView.pausesLocationUpdatesAutomatically = NO;
    
    //保证后台运行
//    _mapView.allowsBackgroundLocationUpdates = YES;
    
     [self.view addSubview:_mapView];
    [self.view addSubview:_statusView.view];
//     [self takePoints];

}


/**
 *  设置导航栏的一些属性
 */
- (void)setupNavigationProperty
{
    // 导航栏中部标题
    self.navigationItem.title = @"酷跑";
    
    
        // 导航栏左侧按钮
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"开始跑步"
                                                                                style:UIBarButtonItemStylePlain
                                                                               target:self
                                                                               action:@selector(startTrack)];

    
        // 导航栏右侧按钮
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"停止跑步"
                                                                                 style:UIBarButtonItemStylePlain
                                                                                target:self
                                                                                action:@selector(stopTrack)];
  
    
    
    
}


/**
 *  开启高德地图定位服务
 */
- (void)startTrack
{
    // 1.清理上次遗留的轨迹路线以及状态的残留显示
    [self clean];
    
    // 2.打开定位服务
    // 显示定位图层
    self.mapView.showsUserLocation = YES;
    
    MACoordinateRegion region = MACoordinateRegionMakeWithDistance(_mapView.centerCoordinate, 1600*2, 1600*2);
    region = [_mapView regionThatFits:region];
    [_mapView setRegion:region animated:YES];
    // 5.如果计时器在计时则复位
    
    if ([self.statusView.timerLabel counting] || self.statusView.timerLabel.text != nil) {
        [self.statusView.timerLabel reset];
    }
    
    
    // 6.开始计时
    [self.statusView.timerLabel start];
    
    //设置轨迹记录状态为：开始
    self.trail = TrailStart;
    
    
}
//定位
-(void)initControls{
    
    
    _lodationButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    _lodationButton.frame = CGRectMake(10, CGRectGetHeight(_mapView.bounds) - 80 , 40, 40);
    
    _lodationButton.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin;
    _lodationButton.backgroundColor = [UIColor whiteColor];
    
    _lodationButton.layer.cornerRadius = 20;
    _lodationButton.layer.masksToBounds = YES;
    _lodationButton.alpha = 0.6;
    
    
    [_lodationButton addTarget:self action:@selector(locationAction) forControlEvents:UIControlEventTouchUpInside];
    
    [_lodationButton setImage:[UIImage imageNamed:@"location_no"] forState:UIControlStateNormal];
    
    
    [_mapView addSubview:_lodationButton];

    
}

-(void)stopTrack{
    
    // 1.停止计时器
    [self.statusView.timerLabel pause];
    
    //设置轨迹记录状态为：结束
    self.trail = TrailEnd;
    
    //关闭定位服务
    _mapView.showsUserLocation = NO;
    
    //添加终点
    self.endPoint = [self creatPointWithLocaiton:self.preLocation title:@"终点"];
    
}


/**
 *  定位失败会调用该方法
 *
 *  @param error 错误信息
 */
-(void)didFailToLocateUserWithError:(NSError *)error{
    
    NSLog(@"did failed locate, error is %@", [error localizedDescription]);
//    UIAlertView *gpsWeaknessWarning = [[UIAlertView alloc]initWithTitle:@"Positioning Failed" message:@"Please allow to use your Location via Setting->Privacy->Location" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Positioning Failed" message:@"Please allow to use your Location via Setting->Privacy->Location" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"YES" style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:alertAction];
    
    
}

#if 0
-(MAPointAnnotation *)creatPointWithLocation:(CLLocation *)location title:(NSString *)title{
    
    MAPointAnnotation *point = [[MAPointAnnotation alloc] init];
    point.coordinate = location.coordinate;
    
    
    return point;
}


-(void)locationAction{
    
    if (_mapView.userTrackingMode == MAUserTrackingModeFollow) {
        [_mapView setUserTrackingMode:MAUserTrackingModeNone];
    }else{
        [_mapView setUserTrackingMode:MAUserTrackingModeFollow];
    }
    
}

-(void)mapView:(MAMapView *)mapView didChangeUserTrackingMode:(MAUserTrackingMode)mode animated:(BOOL)animated{
    
    if (mode == MAUserTrackingModeNone) {
        [_lodationButton setImage:[UIImage imageNamed:@"location_no"] forState:UIControlStateNormal];
    }else{
        
        [_lodationButton setImage:[UIImage imageNamed:@"location_yes"] forState:UIControlStateNormal];
        
    }
    
}


#pragma mark - 获取地图点
-(void)takePoints{
    NSLog(@"affasfafa");

    
//    NSMutableArray *mutableArray = [[NSMutableArray alloc] init];
//    for (int i = 0; i < self.record.numOfLocations; i++) {
//        NSValue *value = [NSValue valueWithMAMapPoint:MAMapPointForCoordinate(self.record.coordinates[i])];
//        [mutableArray addObject:value];
//    }
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths lastObject];
    
    NSString *str = [NSString stringWithFormat:@"run%ld%.f%.f", self.data.time.integerValue, self.data.distance.doubleValue, self.data.speed.doubleValue];
    
    path = [path stringByAppendingString:[NSString stringWithFormat:@"/%ld.plist", [str hash]]];
    NSLog(@"%@", path);
    
    self.points = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    PointsModel *firstPointModel = [self.points firstObject];
    PointsModel *lastPointModel = [self.points lastObject];
    
    CLLocationCoordinate2D firstPoint = CLLocationCoordinate2DMake(firstPointModel.latitude, firstPointModel.longitude);
   CLLocationCoordinate2D lastPoint = CLLocationCoordinate2DMake(lastPointModel.latitude, lastPointModel.longitude);
    
    
//    [_mapView setCenterCoordinate:firstPoint animated:YES];
    
    MAPointAnnotation *startAnimation = [[MAPointAnnotation alloc] init];
    startAnimation.coordinate = firstPoint;
    [_mapView addAnnotation:startAnimation];
    
    MAPointAnnotation *endAnimation = [[MAPointAnnotation alloc] init];
    endAnimation.coordinate = lastPoint;
    [_mapView addAnnotation:endAnimation];
    
    
    
    //画线
    CLLocationCoordinate2D polyLineCoords[self.points.count];
    for (int i = 0; 1 < self.points.count; i++) {
        PointsModel *model = self.points[i];
        CLLocationCoordinate2D point = CLLocationCoordinate2DMake(model.latitude, model.longitude);
        polyLineCoords[i] = point;
    }
    
    MAPolyline *polyLine = [MAPolyline polylineWithCoordinates:polyLineCoords count:self.points.count];
    [_mapView addOverlay:polyLine];
    
    
    self.averageSpeed = [self.record totalDistance] / [self.record totalDuration];
}

-(void)setRecord:(WHRecord *)record{
    
    _record = record;
    
}

#pragma mark - 地图画线

-(MAOverlayView *)mapView:(MAMapView *)mapView viewForOverlay:(id<MAOverlay>)overlay{
    if ([overlay isKindOfClass:[MAPolyline class]]) {
        
        MAPolylineView *polylineView = [[MAPolylineView alloc] initWithPolyline:overlay];
        
        //线宽
        polylineView.lineWidth = 3.f;
        polylineView.strokeColor = [UIColor colorWithRed:0 green:0 blue:1 alpha:1.000];
        
//        polylineView.lineJoinType = kCGLineJoinRound;//连接类型
//        polylineView.lineCapType = kCGLineCapRound;// 点的类型
//        
        return polylineView;
        
    }
    
    return nil;
}
#endif
/**
 *  用户位置更新后，会调用此函数
 *  @param userLocation 新的用户位置
 */
-(void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation{
    
    if (CLLocationCoordinate2DIsValid(CLLocationCoordinate2DMake(userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude))) {
        
        [_mapView setCenterCoordinate:CLLocationCoordinate2DMake(userLocation.location.coordinate.latitude,  userLocation.location.coordinate.longitude) animated:YES];
    }
    
    //  动态更新我的位置数据
    NSLog(@"La:%f, Lo:%f", userLocation.location.coordinate.latitude,  userLocation.location.coordinate.longitude);
    
    NSLog(@"king");
    //  如果精准度不在10米范围内
    if (userLocation.location.horizontalAccuracy > kCLLocationAccuracyNearestTenMeters) {
        NSLog(@"userLocation.location.horizontalAccuracy is %f", userLocation.location.horizontalAccuracy);
        return;
    }
    
    [self startTrailRouteWithUserLocation:userLocation];
}

#pragma mark - Selector for didUpdateBMKUserLocation:
- (void)startTrailRouteWithUserLocation:(MAUserLocation *)userLocation{
    
    if (self.preLocation) {
        
        // 计算本次定位数据与上次定位数据之间的时间差
        NSTimeInterval dtime = [userLocation.location.timestamp timeIntervalSinceDate:self.preLocation.timestamp];
        
        // 累计步行的时间
        self.sumTime += dtime;
        
        CGFloat distance = [userLocation.location distanceFromLocation:self.preLocation];
        NSLog(@"与上一位置点的距离为：%f", distance);
        
        
        if (distance < 5) {
            NSLog(@"与前一更新点距离小于5m，直接返回该方法");
            return;
        }
        
        // 累加步行距离
        self.sumDistance += distance;
        self.statusView.distance.text = [NSString stringWithFormat:@"%.2f", distance * 0.001];
        
        //计算移动速度
        CGFloat speed = distance / dtime;
        self.statusView.moveSpeedLabel.text = [NSString stringWithFormat:@"%.2f", speed];
        
        // 计算平均速度
        CGFloat avgSpeed = self.sumDistance / self.sumTime;
        self.statusView.speedLabelKM.text = [NSString stringWithFormat:@"%.2f", avgSpeed];
    }
    
    
    // 将符合的位置点存储到数组中
    if (userLocation.location != nil) {
        [self.locationArrayM addObject:userLocation.location];
    }
    
    self.preLocation = userLocation.location;
    
    // 绘图
    [self drawWalkPolyline];
}

- (void)drawWalkPolyline{
    
    // 轨迹点
    NSInteger count = self.locationArrayM.count;
    
     // 手动分配存储空间，结构体：地理坐标点，用直角地理坐标表示 X：横坐标 Y：纵坐标
    // new 的使用 把文件后缀改为 .mm
    MAMapPoint *tempPoints = new MAMapPoint[count];
    
    [self.locationArrayM enumerateObjectsUsingBlock:^(CLLocation *location, NSUInteger idx, BOOL * stop) {
        
        /*!
         @brief 经纬度坐标转平面投影坐标
         @param coordinate 要转化的经纬度坐标
         @return 平面投影坐标
         */
        MAMapPoint locationPoint = MAMapPointForCoordinate(location.coordinate);
        tempPoints[idx] = locationPoint;
        
        //放置起点旗帜
        if (0 == idx && TrailStart == self.trail && self.startPoint == nil) {
            self.startPoint = [self creatPointWithLocaiton:location title:@"起点"];
        }
    }];
    
       //移除原有的绘图
    if (self.polyLine) {
        [self.mapView removeOverlay:self.polyLine];
    }
    // 通过points构建MAPolyline
    self.polyLine = [MAPolyline polylineWithPoints:tempPoints count:count];
    
    //添加路线，绘图
    if (self.polyLine) {
        [self.mapView addOverlay:self.polyLine];
    }
    
    // 清空 tempPoints 内存
    delete [] tempPoints;
    
    [self mapViewFitPolyLine:self.polyLine];
}

// 添加一个大头针

- (MAPointAnnotation *)creatPointWithLocaiton:(CLLocation *)location title:(NSString *)title;
{
    NSLog(@"大头针");
    MAPointAnnotation *point = [[MAPointAnnotation alloc] init];
    point.coordinate = location.coordinate;
    point.title = title;
    [self.mapView addAnnotation:point];
    
    return point;
}
-(void)clean{
    
    //清空状态信息
    self.statusView.distance.text = nil;
    self.statusView.speedLabelKM.text = nil;
    self.statusView.moveSpeedLabel.text = nil;
    
    //清空数组
    [self.locationArrayM removeAllObjects];
    
    [self.mapView removeAnnotation:self.startPoint];
    self.startPoint = nil;
    
    [self.mapView removeAnnotation:self.endPoint];
    self.endPoint = nil;
    
    [self.mapView removeAnnotation:self.polyLine];
    self.polyLine = nil;
    
    [self.mapView removeAnnotations:self.mapView.annotations];
    
}


/**
 *  根据polyline设置地图范围
 *
 *  @param polyLine
 */
- (void)mapViewFitPolyLine:(MAPolyline *) polyLine {
    CGFloat ltX, ltY, rbX, rbY;
    if (polyLine.pointCount < 1) {
        return;
    }
    MAMapPoint pt = polyLine.points[0];
    ltX = pt.x, ltY = pt.y;
    rbX = pt.x, rbY = pt.y;
    for (int i = 1; i < polyLine.pointCount; i++) {
        MAMapPoint pt = polyLine.points[i];
        if (pt.x < ltX) {
            ltX = pt.x;
        }
        if (pt.x > rbX) {
            rbX = pt.x;
        }
        if (pt.y > ltY) {
            ltY = pt.y;
        }
        if (pt.y < rbY) {
            rbY = pt.y;
        }
    }
    MAMapRect rect;
    rect.origin = MAMapPointMake(ltX , ltY);
    rect.size = MAMapSizeMake(rbX - ltX, rbY - ltY);
    [self.mapView setVisibleMapRect:rect];
    self.mapView.zoomLevel = self.mapView.zoomLevel - 0.3;
}


-(MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay{
    
    if ([overlay isKindOfClass:[MAPolyline class]]) {
        
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithOverlay:overlay];
        polylineRenderer.lineWidth = 8.f;
        polylineRenderer.strokeColor = [[UIColor redColor] colorWithAlphaComponent:0.7];
        return polylineRenderer;
        
    }
    
    return nil;
}


-(MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation{
    
    if ([annotation isKindOfClass:[MAPointAnnotation class]]) {
        static NSString *pointReuseIndentifier = @"pointReuseIndentifier";
        
        MAPinAnnotationView *annationView = (MAPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
        
        if (annationView == nil) {
            annationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
        }
        
        // 大头针的颜色
        annationView.pinColor = MAPinAnnotationColorGreen;
        
        // 从天上掉下的效果
        annationView.animatesDrop = YES;
        // 不可拖拽
        annationView.draggable = NO;
        
        return annationView;
        
    }

    return nil;
}

- (NSMutableArray *)locationArrayM
{
    if (_locationArrayM == nil) {
        _locationArrayM = [NSMutableArray array];
    }
    
    return _locationArrayM;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
